package com.assetmanage.controller;

import com.assetmanage.utils.Result;
import com.google.gson.Gson;
import com.fasterxml.jackson.databind.ObjectMapper;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Method;

public class BaseServlet extends HttpServlet {
    protected static final Gson GSON = new Gson();
    protected static final ObjectMapper MAPPER = new ObjectMapper();

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 设置请求和响应的编码
        req.setCharacterEncoding("UTF-8");
        resp.setContentType("application/json;charset=UTF-8");

        try {
            // 获取请求的方法名
            String methodName = req.getParameter("method");
            if (methodName == null) {
                // 如果没有method参数，尝试从URL路径中获取
                String pathInfo = req.getPathInfo();
                if (pathInfo != null && pathInfo.length() > 1) {
                    methodName = pathInfo.substring(1);
                }
            }

            if (methodName == null || methodName.isEmpty()) {
                writeError(resp, "方法名不能为空");
                return;
            }

            // 获取方法对象
            Method method = this.getClass().getMethod(methodName, HttpServletRequest.class, HttpServletResponse.class);
            // 执行方法
            method.invoke(this, req, resp);
        } catch (Exception e) {
            e.printStackTrace();
            writeError(resp, "服务器内部错误：" + e.getMessage());
        }
    }

    // 写入成功响应
    protected void writeSuccess(HttpServletResponse resp, Object data) throws IOException {
        writeJson(resp, Result.success(data));
    }

    // 写入错误响应
    protected void writeError(HttpServletResponse resp, String message) throws IOException {
        writeJson(resp, Result.error(message));
    }

    protected void writeJson(HttpServletResponse resp, Object obj) throws IOException {
        resp.setContentType("application/json;charset=utf-8");
        PrintWriter out = resp.getWriter();
        out.write(GSON.toJson(obj));
        out.flush();
    }
} 